//
//  JCConversationCell.swift
//  JChat
//
//  Created by JIGUANG on 2017/3/22.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import JMessage
import MTCategory
import Kingfisher

class JCConversationCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = UIColor.theme.background
        selectionStyle = .none
        _init()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        _init()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        _init()
    }

    private lazy var avatorView: UIImageView = {
        let avatorView = UIImageView()
        avatorView.contentMode = .scaleAspectFill
        avatorView.layer.cornerRadius = 22
        avatorView.layer.masksToBounds = true
        return avatorView
    }()
    
    private lazy var statueView: UIImageView = UIImageView()
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.textColor = UIColor.text.x1d1a1a
        titleLabel.font = PingFangSCSemiboldFont(14)
        return titleLabel
    }()
    private lazy var msgLabel: UILabel = {
        let msgLabel = UILabel()
        msgLabel.textColor = UIColor.text.x9b9b9b
        msgLabel.font = PingFangSCMediumFont(12)
        return msgLabel
    }()
    private lazy var dateLabel: UILabel = {
        let dateLabel = UILabel()
        dateLabel.textAlignment = .right
        dateLabel.font = PingFangSCMediumFont(10)
        dateLabel.textColor = UIColor.text.x9b9b9b
        dateLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return dateLabel
    }()
    private lazy var redPoin: UILabel = {
        let redPoin = UILabel(frame: CGRect(x: 65 - 17, y: 4.5, width: 20, height: 20))
        redPoin.textAlignment = .center
        redPoin.font = UIFont.systemFont(ofSize: 11)
        redPoin.textColor = .white
        redPoin.layer.backgroundColor = UIColor.chat.xff003d.cgColor
        redPoin.textAlignment = .center
        return redPoin
    }()
    
    lazy var lineView: UIView = {
        let v: UIView = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        return v
    }()
    
    lazy var isMyClubLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(10)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "我的"
        l.isHidden = true
        l.textAlignment = .center
        return l
    }()
    
    override func prepareForReuse() {
        super.prepareForReuse()
        msgLabel.text = ""
    }
    
    //MARK: - public func
    open func bindConversation(_ conversation: JMSGConversation) {
        statueView.isHidden = true
        let isGroup = conversation.ex.isGroup
        if conversation.unreadCount != nil && (conversation.unreadCount?.intValue)! > 0 {
            redPoin.isHidden = false
            var text = ""
            if (conversation.unreadCount?.intValue)! > 99 {
                text = "99+"
                redPoin.layer.cornerRadius = 9.0
                redPoin.layer.masksToBounds = true
            } else {
                redPoin.layer.cornerRadius = 9.0
                redPoin.layer.masksToBounds = true
                text = "\(conversation.unreadCount!)"
            }
            redPoin.text = text
            
            var isNoDisturb = false
            if isGroup {
                if let group = conversation.target as? JMSGGroup {
                    isNoDisturb = group.isNoDisturb
                }
            } else {
                if let user = conversation.target as? JMSGUser {
                    isNoDisturb = user.isNoDisturb
                }
            }
            
//            if isNoDisturb {
//                redPoin.layer.cornerRadius = 4.0
//                redPoin.layer.masksToBounds = true
//                redPoin.text = ""
//                redPoin.frame = CGRect(x: 65 - 5, y: 4.5, width: 8, height: 8)
//            }
        } else {
            redPoin.isHidden = true
        }
        
        if let latestMessage = conversation.latestMessage {
            let time = latestMessage.timestamp.intValue / 1000
            let date = Date(timeIntervalSince1970: TimeInterval(time))
            dateLabel.text = date.conversationDate()
        } else {
            dateLabel.text = ""
        }
        
        
        /// 消息类型提示
        if let messageType: JMSGContentType = conversation.latestMessage?.contentType {
            var prefix = ""
            if let lastMessage = conversation.latestMessage {
                prefix = (lastMessage.fromUser.isEqual(to: JMSGUser.myInfo()) == false) ? lastMessage.fromUser.displayName() + ":" : ""
            }
            if conversation.ex.isSingle {
                prefix = ""
            }
            
            var redpacketTips = ""
            if conversation.ex.isGroup {
                if let group = conversation.target as? JMSGGroup {
                    if let desc = group.desc {
                        if !desc.contains("|.>p_t_g<.|") {
                            redpacketTips = "往俱乐部里撒了"
                        } else {
                            redpacketTips = "往聚会任务群里撒了"
                        }
                    }
                }
            }
            
            if messageType == .custom {
                let content: JMSGCustomContent = conversation.latestMessage?.content as! JMSGCustomContent
                switch content.customMsgType() {
                case .gift, .pullGift, .giftnotify:
                    msgLabel.text = prefix + "[礼物]"
                case .redpack:
                    var msgText = "", conversationTypeString = ""
                    if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any>, conversation.latestMessage?.fromUser.isEqual(to: JMSGUser.myInfo()) == false {
                        if let conversationType: Int = dict["targetType"] as? Int {
                            conversationTypeString = conversationType == 1 ? "向你撒了" : conversationType == 2 ? redpacketTips : "往广场撒了"
                        }
                        if let redpackC: Int = dict["money"] as? Int {
                            
                            let unredCount: String = conversation.unreadCount?.intValue ?? 0 > 1 ? "[\(conversation.unreadCount!.stringValue)条]" : ""
                            
                            if isGroup {
                                if let latestMessage = conversation.latestMessage {
                                    let fromUser = latestMessage.fromUser
                                    if !fromUser.isEqual(to: JMSGUser.myInfo()) &&
                                        latestMessage.contentType != .eventNotification &&
                                        latestMessage.contentType != .prompt {
                                        msgText = "\(unredCount)\(conversation.latestMessage!.fromUser.displayName())\(conversationTypeString)\(redpackC)钻石"
                                    }
                                }
                            } else {
                                msgText = "\(conversationTypeString)\(redpackC)钻石"
                            }
                            
                            msgLabel.text = msgText
                            msgLabel.textColor = UIColor.text.xfed600
                        }
                        
                    } else {
                        msgLabel.text = prefix + "[红包]"
                        msgLabel.textColor = .red
                    }
                case .pullNotify:
                    if let infos : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                        if let senderUserName: String = infos["senderUserName"] as? String,
                            let pullNickname: String = infos["pullNickname"] as? String,
                            let senderNickname: String = infos["senderNickname"] as? String {
                            
                            let isSelf: Bool = (senderUserName == JMSGUser.myInfo().username)
                            /// 如果是自己发的红包
                            if isSelf {
                                if let pullUserName = infos["pullUserName"] as? String {
                                    /// 自己领取了自己发的红包
                                    if senderUserName == pullUserName {
                                        msgLabel.text = "你领取了自己发的红包"
                                        msgLabel.textColor = UIColor.text.x999999
                                    } else {
                                        msgLabel.text = "\(pullNickname)领取了你的红包"
                                        msgLabel.textColor = UIColor.text.x999999
                                    }
                                } else {
                                   msgLabel.text = "\(pullNickname)领取了你的红包"
                                    msgLabel.textColor = UIColor.text.x999999
                                }
                            } else {
                                /// 不是自己发的红包
                                if let pullUserName = infos["pullUserName"] as? String {
                                    /// 是自己领取的
                                    if JMSGUser.myInfo().username == pullUserName {
                                        msgLabel.text = " 你领取了\(senderNickname)的红包"
                                        msgLabel.textColor = UIColor.text.x999999
                                    } else {
                                        msgLabel.text = "\(pullNickname)领取了\(senderNickname)的红包"
                                        msgLabel.textColor = UIColor.text.x999999
                                    }
                                }
                            }
                        }
                    }
                case .activity:
                    if let infos : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                        //"[\"activityId\": 55, \"sendUserHeadUrl\": 龟虽寿, \"sendUserNickname\": mitu_2tYyu3Hp, \"messageType\": activity, \"activityInfo\": 大家老残门口可能不会沟沟壑壑哈哈哈哈哈哈哈哈哈, \"activityName\": 宝贝好]"
                        
                        if isGroup {
                            let unredCount: String = conversation.unreadCount?.intValue ?? 0 > 1 ? "[\(conversation.unreadCount!.stringValue)条]" : ""
                            if let activityName = infos["activityName"] as? String {
                                if let latestMessage = conversation.latestMessage {
                                    let fromUser = latestMessage.fromUser
                                    if latestMessage.contentType != .eventNotification &&
                                        latestMessage.contentType != .prompt {
                                        if !fromUser.isEqual(to: JMSGUser.myInfo()) {
                                            msgLabel.textColor = UIColor.text.x999999
                                            msgLabel.text = "\(unredCount)\(conversation.latestMessage!.fromUser.displayName())发起了\"\(activityName)\"[活动]"
                                        } else {
                                            msgLabel.textColor = UIColor.text.x999999
                                            msgLabel.text = "\(unredCount)你发起了\"\(activityName)\"[活动]"
                                        }
                                    }
                                }
                            }
                        }
                    }
                case .task:
                if let infos : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    msgLabel.textColor = UIColor.text.x999999
                    if let name = infos["partyName"] as? String, let money = infos["partyGiftNum"] {
                        msgLabel.text = prefix + "[" + name + "] 聚会任务"
                    }
                }
                default:
                    break
                }
            } else {
                if isGroup {
                    if let latestMessage = conversation.latestMessage {
                        let fromUser = latestMessage.fromUser
                        if !fromUser.isEqual(to: JMSGUser.myInfo()) &&
                            latestMessage.contentType != .eventNotification &&
                            latestMessage.contentType != .prompt {
                            
                            var infomation = conversation.latestMessageContentText()
                            infomation = infomation.replacingOccurrences(of: ",", with: "、")
                            infomation = infomation.replacingOccurrences(of: "，", with: "、")
                            let unredCount: String = conversation.unreadCount?.intValue ?? 0 > 1 ? "[\(conversation.unreadCount!.stringValue)条]" : ""
                            msgLabel.text = "\(unredCount)\(fromUser.displayName()): \(infomation)"
                            
                        } else {
                            var infomation = conversation.latestMessageContentText()
                            if let group: JMSGGroup = conversation.target as? JMSGGroup {
                                /// 是俱乐部
                                if let desc = group.desc, !desc.contains("|.>p_t_g<.|") {
                                    infomation = infomation.replacingOccurrences(of: "群聊", with: "俱乐部")
                                    infomation = infomation.replacingOccurrences(of: "群", with: "俱乐部")
                                } else {
                                    infomation = infomation.replacingOccurrences(of: "群聊", with: "聚会任务群")
//                                    infomation = infomation.replacingOccurrences(of: "群", with: "聚会任务群")
                                }
                                
                            }
                            
                            msgLabel.text = infomation.trim(trimNewline: true)
                            msgLabel.textColor = UIColor.text.x999999
                        }
                        
                        if conversation.unreadCount != nil &&
                            conversation.unreadCount!.intValue > 0 &&
                            latestMessage.contentType != .prompt {
                            if latestMessage.isAtAll() {
                                msgLabel.attributedText = getAttributString(attributString: "[@所有人]", string: msgLabel.text!)
                            } else if latestMessage.isAtMe() {
                                msgLabel.attributedText = getAttributString(attributString: "[有人@我]", string: msgLabel.text!)
                            }
                        }
                    } else {
                        msgLabel.text = ""
                    }
                } else {
                    switch messageType {
                    case .image:
                        msgLabel.text = prefix + "[图片]"
                    case .text:
                        let infomation = conversation.latestMessageContentText()
                        msgLabel.text = prefix + infomation.trim(trimNewline: true)
                    default:
                        let infomation = conversation.latestMessageContentText()
                        msgLabel.text = prefix + infomation.trim(trimNewline: true)
                    }
                    msgLabel.textColor = UIColor.text.x999999
                }
            }
        }
        
        if let draft = JCDraft.getDraft(conversation) {
            if !draft.isEmpty && draft != AppPlaceholder.inputViewPlaceholder {
                msgLabel.attributedText = getAttributString(attributString: "[草稿]", string: draft)
            }
        }

        if !isGroup {
            let user = conversation.target as? JMSGUser
            titleLabel.text = user?.displayName() ?? ""
//            avatorView.layer.cornerRadius = 22
//            avatorView.layer.masksToBounds = true
//            user?.thumbAvatarData { (data, username, error) in
//                guard let imageData = data else {
//                    self.avatorView.image = self.userDefaultIcon
//                    return
//                }
//                let image = UIImage(data: imageData)
//                self.avatorView.image = image
//            }
            self.avatorView.mtSetImage(user?.avatar, nil)
        } else {
            if let group = conversation.target as? JMSGGroup {
                titleLabel.text = group.displayName()
                if group.isShieldMessage {
                    statueView.isHidden = false
                }
                
                group.thumbAvatarData { (data, s, e) in
                    if let data = data {
                        self.avatorView.image = UIImage(data: data)
                    } else {
                        self.avatorView.image = UIImage(named: defaultPlaceholderIcon60x60)
                    }
                }
            }
        }

//        if conversation.ex.isSticky {
//            backgroundColor = UIColor(hex: 0xF5F6F8)
//        } else {
//            backgroundColor = .white
//        }
    }
    
    /* 没有缓存的俱乐部头像的时候
    * 俱乐部头像缓存更新策略
    * 只有增加成员的情况下更新头像
    *
    */
    private func downImage(target: JMSGGroup) {
        MTGroupImageDownLoadTool.downImage(target) { [weak self] (images) in
            guard let weakSelf = self else { return }
            var resultImage: UIImage = weakSelf.groupDefaultIcon!
            if images.count > 0 {
                resultImage = MTWeChatAvatorTool.stitchImage(images: images, size: CGSize(width: 200, height: 200), backgroundColor: UIColor.clear, gap: 0)
                KingfisherManager.shared.cache.store(resultImage, forKey: target.gid)
                DispatchQueue.main.async {
                    weakSelf.avatorView.image = resultImage
                }
                
            } else {
                DispatchQueue.main.async {
                    weakSelf.avatorView.image = resultImage
                }
            }
        }
    }
    
    func getAttributString(attributString: String, string: String) -> NSMutableAttributedString {
        let attr = NSMutableAttributedString(string: "")
        var attrSearchString: NSAttributedString!
        attrSearchString = NSAttributedString(string: attributString, attributes: convertToOptionalNSAttributedStringKeyDictionary([ convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor) : UIColor(hex: 0xf9f9f9), convertFromNSAttributedStringKey(NSAttributedString.Key.font) : PingFangSCRegularFont(12)]))
        attr.append(attrSearchString)
        attr.append(NSAttributedString(string: string))
        return attr
    }
    
    private lazy var groupDefaultIcon = UIImage(named: defaultPlaceholderIcon60x60)
    private lazy var userDefaultIcon = UIImage(named: defaultPlaceholderIcon60x60)
    
    //MARK: - private func
    private func _init() {
        avatorView.image = userDefaultIcon
        statueView.image = UIImage.loadImage("com_icon_shield")
        
        contentView.addSubview(avatorView)
        avatorView.addSubview(isMyClubLabel)
        
        contentView.addSubview(statueView)
        contentView.addSubview(titleLabel)
        contentView.addSubview(msgLabel)
        contentView.addSubview(dateLabel)
        contentView.addSubview(redPoin)
        contentView.addSubview(lineView)
        
        avatorView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.width.height.equalTo(44)
        }
        
        isMyClubLabel.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(12)
        }
        
        redPoin.snp.makeConstraints { (make) in
            //make.centerX.equalTo(avatorView.snp.right).offset(-5)
            //make.centerY.equalTo(avatorView.snp.top).offset(5)
            make.width.height.equalTo(16)
            make.right.equalTo(dateLabel)
            make.centerY.equalTo(msgLabel)
            
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(contentView.snp.centerY).offset(-2)
            make.left.equalTo(avatorView.snp.right).offset(10)
            make.right.equalTo(dateLabel.snp.left).offset(-24)
            make.height.equalTo(20)
        }
        
        msgLabel.snp.makeConstraints { (make) in
            make.height.left.right.equalTo(titleLabel)
            make.top.equalTo(contentView.snp.centerY).offset(2)
            make.right.equalTo(dateLabel.snp.left).offset(-24)
        }
        
        dateLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(titleLabel)
            make.right.equalToSuperview().offset(-10)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
//
//        addConstraint(_JCLayoutConstraintMake(statueView, .top, .equal, dateLabel, .bottom, 7))
//        addConstraint(_JCLayoutConstraintMake(statueView, .right, .equal, contentView, .right, -16))
//        addConstraint(_JCLayoutConstraintMake(statueView, .height, .equal, nil, .notAnAttribute, 12))
//        addConstraint(_JCLayoutConstraintMake(statueView, .width, .equal, nil, .notAnAttribute, 12))
    }
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
	guard let input = input else { return nil }
	return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
	return input.rawValue
}
